import {Row, Col, message} from 'antd';
// import message from '../../_antd1.11.2/message';
import {defaultIcon,splitUserInfo,createQRCode} from './util/index'
// import Row from '../../_antd1.11.2/row'
// import Col from '../../_antd1.11.2/col'

class WeaPopoverHrm extends React.Component {
	static contextTypes = {
		router: React.PropTypes.routerShape
	}
	listenRouter(){
		this.context.router.listen(nextState => {
			const { path } = this.state;
			const { pathname } = nextState;
			if(path !== pathname){
				this.setState({path:pathname,visible:false});
			}
		})
	}
	constructor(props) {
		super(props);
		this.state = {
			random: `${new Date().getTime()}_${Math.ceil(Math.random() * 100000)}`,

			userid: '',
			userinfo: '',
			visible: false,
			showSQR: false,
			x:-1000,
			y:-1000,
			loading: false,
			imgLoading: false,
			targetHeight: 0,
			targetWidth: 0,

			pWidth: 0,
			pHeight: 0,
			pTop: 0,
			pLeft: 0,

			showBigImg: false,
			bigImgWidth: 187,
			bigImgHeight: 288,
			path: window.location.hash && window.location.hash.split('#/')[1].split('?')[0]
		}
		this.onError = this.onError.bind(this);
		this.onLoad = this.onLoad.bind(this);
	}
	componentDidMount(){
		this.listenRouter();

		let pointerXYOld = null;
		if(typeof window.pointerXY === 'function'){
			pointerXYOld = window.pointerXY;
		}
    	window.pointerXY = e =>{
    		const { random } = this.state;
    		//if(jQuery(e.target).closest('.wea-popover-hrm-relative-parent')[0].id === `wea_popover_hrm_${random}`){
    			this.setState({
    				x: jQuery(e.target).offset().left,
    				y: jQuery(e.target).offset().top,
    				targetWidth: e.target.offsetWidth,
    				targetHeight: e.target.offsetHeight,
    				visible: true
    			})
    		//}
    		pointerXYOld && pointerXYOld(e);
    	}

		let openhrmOld = null;
		if(typeof window.openhrm === 'function'){
			openhrmOld = window.openhrm;
		}
		window.openhrm = id =>{
    		this.getParentStyle()
			let change = id && this.state.userid !== id;
			let initStates = change ? {loading: true,imgLoading: true, userid:id, userinfo: '',showBigImg: false} : {};
			this.setState(initStates);
			if(change){
				jQuery.get("/hrm/resource/simpleHrmResourceTemp.jsp?userid=" + id,
			        result =>{
			            let userinfo = splitUserInfo(result);
		                if (!userinfo.userimg) {
		                    userinfo.userimg = defaultIcon[userinfo.sex]
		                }
		                this.setState({userinfo,loading:false,imgLoading:false});
			            createQRCode(userinfo)
			    })
			}
			openhrmOld && openhrmOld(id)
		}

    	this.getParentStyle()
    	jQuery(window).resize(() => {
		    this._reactInternalInstance !== undefined && this.getParentStyle();
		});
    }
	getParentStyle(){
		const { children } = this.props;
    	let com = children ? jQuery('.wea-popover-hrm-relative-parent') : '';
    	if(com){
			this.setState({
				pWidth: com.width(),
				pHeight: com.height(),
				pTop: com.offset().top,
				pLeft: com.offset().left,
			})
    	}
	}
	onLoad(e){
		let bigImgWidth = e.target.naturalWidth || 187;
		let bigImgHeight = e.target.naturalHeight || 288;
		this.setState({ bigImgWidth, bigImgHeight })
	}
	onError(){
		let { userinfo } = this.state;
		userinfo.userimg = defaultIcon[userinfo.sex];
		this.setState({ userinfo })
	}
	render(){
		const { children } = this.props;
		const { userid, userinfo, showSQR, visible, x, y, targetWidth, targetHeight, loading, imgLoading,
			pWidth, pHeight, pTop, pLeft, showBigImg, bigImgWidth, bigImgHeight, random} = this.state;
		const _pHeight = pHeight || 0;
		const _pLeft = pLeft || 0;
		const _pTop = pTop || 0;
		const sex = {'Mr.':'（ 男 ）','Ms.':'（ 女 ）'};
		const winW = document.body.clientWidth;
    	const winH = document.body.clientHeight;
		const nowStyle = children ?
		{
			display: visible ? 'block' : 'none',
    		position : 'absolute',
    		left: winW - x <= 500 ? (winW - 500) : (x - _pLeft),
    		top: winH - y <= 293 ? (y - 293 - _pTop) : (y + targetHeight  - _pTop)
		} : {
    		display: visible ? 'block' : 'none',
    		position : 'fixed',
    		left: winW - x <= 500 ? (winW - 500) : x,
    		top: winH - y <= 293 ? (y - 293) : (y + targetHeight)
    	};
//  	if(bigImgWidth >= bigImgHeight){ // 宽图
//  		let bigWidth = bigImgWidth > winW * 0.8 ? winW * 0.8 : bigImgWidth;
//  		let bigHeight = bigWidth * bigImgHeight / bigImgWidth;
//  	}else{ // 长图
		const bigHeight = bigImgHeight > winH * 0.8 ? winH * 0.8 : bigImgHeight;
		const bigWidth = bigHeight * bigImgWidth / bigImgHeight;
//  	}
		const bigImgStyle = showBigImg ? {
			width: bigWidth,
			height: bigHeight,
    		left: nowStyle.left + bigWidth >= winW  - (children ? _pLeft : 0) ? (winW - (children ? _pLeft : 0) - bigWidth - nowStyle.left - 20) : (bigWidth > 187 ? (((bigWidth - 187) / 2) > (nowStyle.left + _pLeft) ? -(nowStyle.left + _pLeft - 20) : ((187 - bigWidth) / 2)) : -2),
    		top: nowStyle.top + bigHeight >= winH - (children ? _pTop : 0) ? (winH - (children ? _pTop : 0) - bigHeight - nowStyle.top - 20) : (bigHeight > 288 ? ((288 - bigHeight) / 2) : -2),
			opacity: 1,
			transformOrigin: '50% 50%',
			transition: 'all .3s ease-in-out'
		} : {
			width: '100%',
			height: '100%',
    		left: 0,
    		top: 0,
    		opacity: 0,
    		transition: 'all .2s ease-in-out'
		};
		return <div className='wea-popover-hrm-relative-parent' id={`wea_popover_hrm_${random}`}>
			{children ? children : ''}
			<div className='wea-popover-hrm-wrapper' style={nowStyle}>
				<img className="wea-popover-hrm-close" src="/images/messageimages/temp/closeicno_wev8.png" onClick={()=>this.setState({visible:false,showBigImg:false,showSQR:false})}/>
				{ userinfo ?
					<Row>
						<Col span={10} style={{height:288}}>
							<img className='wea-popover-hrm-userimg' onClick={()=>{!imgLoading && this.setState({showBigImg: true})}} src={imgLoading ? '/images/messageimages/temp/loading_wev8.gif' : userinfo.userimg} onError={this.onError} onLoad={this.onLoad}/>
							<img className={`wea-popover-hrm-userimg ${showBigImg ? 'wea-popover-hrm-userimg-big' : ''}`} style={bigImgStyle} onClick={()=>{!imgLoading && this.setState({showBigImg: !showBigImg})}} src={imgLoading ? '/images/messageimages/temp/loading_wev8.gif' : userinfo.userimg} onError={this.onError}/>
							<div className='wea-popover-hrm-sqrimg' style={{position:'absolute',top:4,right:5}} onClick={e=>{
								this.setState({showSQR:!showSQR});
								//暂时未测出哪个管用。。
						    	e.stopPropagation && e.stopPropagation();
						    	e.preventDefault && e.preventDefault();
						    	e.nativeEvent && e.nativeEvent.preventDefault();
							}} />
							<div className='wea-popover-hrm-sqr' style={{display: showSQR ? 'block' : 'none'}} onClick={()=>this.setState({showSQR:false})}></div>
							<div className='wea-popover-hrm-btns'>
								<div className='wea-popover-hrm-btn-1' onClick={()=>{sendMsgToPCorWeb(userid, 0, '', '')}} title="发消息"/>
								<div className='wea-popover-hrm-btn-2' onClick={()=>{window.open(`/sms/SmsMessageEdit.jsp?hrmid=${userid}`)}} title="发短信"/>
								<div className='wea-popover-hrm-btn-3' onClick={()=>{window.open(`/email/MailAdd.jsp?isInternal=1&internalto=${userid}`)}} title="发送邮件"/>
								<div className='wea-popover-hrm-btn-4' onClick={()=>{window.open(`/workplan/data/WorkPlan.jsp?resourceid=${userid}&add=1`)}} title="新建日程"/>
							</div>
						</Col>
						<Col span={14} style={{paddingLeft:16}}>
							<div className='wea-popover-hrm-title'>
								<a href={`/hrm/HrmTab.jsp?_fromURL=HrmResource&id=${userid}`} target='_blank' style={{fontSize:14,color:'#018efb'}}>{userinfo.name}</a>
								<span>{`${sex[userinfo.sex]} ${userinfo.code}`}</span>
							</div>
							<div className='wea-popover-hrm-info'>
								<p><span>部门:</span>{userinfo.dept}</p>
								<p><span>分部:</span>{userinfo.sub}</p>
								<p><span>岗位:</span>{userinfo.job}</p>
								<p><span>上级:</span>{userinfo.manager}</p>
								<p><span>状态:</span>{userinfo.status}</p>
								<p><span>手机:</span>{userinfo.mobile}</p>
								<p><span>电话:</span>{userinfo.tel}</p>
								<p><span>邮件:</span>{userinfo.email}</p>
							</div>
						</Col>
					</Row>
					: ''
				}
			</div>
		</div>
	}
}
//								<img style={{marginLeft:20,position:'relative',top:5}} onClick={()=>this.setState({showSQR:!showSQR})} src="/images/messageimages/temp/qcode_wev8.png"/>
//								<div className='wea-popover-hrm-sqr' style={{display: showSQR ? 'block' : 'none'}} onClick={()=>this.setState({showSQR:false})}></div>

export default WeaPopoverHrm;